﻿using System.Windows.Controls;
using System.Diagnostics;

namespace NodeEditor {

    public partial class TextProperty : Grid {

        public delegate void VoidHandler(object v);

        public event VoidHandler valueChanged;

        public TextProperty() {
            InitializeComponent();
        }

        private string _keyName;
        public string keyName {
            get { return _keyName; }
            set { _keyName = keyNameUI.Text = value; }
        }

        private string _keyType;
        public string keyType {
            get { return _keyType; }
            set { 
                _keyType = value; 
                keyTypeUI.Text = $"[{value}]"; 
            }
        }

        private object _value;
        public object value {
            get { return _value; }
        }

        private void fieldUI_TextChanged(object sender, TextChangedEventArgs e) {
            if (_keyType == "Int") {
                int number;
                if (int.TryParse(valueUI.Text, out number)) {
                    _value = number;
                } else {
                    if (valueUI.Text == "") {
                        _value = 0;
                        return;
                    }

                    valueUI.TextChanged -= fieldUI_TextChanged;
                    valueUI.Text = _value == null ? "" : _value.ToString();
                    // 将光标移动到最后一位
                    valueUI.CaretIndex = valueUI.Text.Length;
                    valueUI.TextChanged += fieldUI_TextChanged;
                    return;
                }
            } else if (_keyType == "Float") {
                double d;
                if (double.TryParse(valueUI.Text, out d)) {
                    _value = d;
                } else {
                    if (valueUI.Text == "") {
                        _value = 0;
                        return;
                    }

                    valueUI.TextChanged -= fieldUI_TextChanged;
                    valueUI.Text = _value == null ? "" : _value.ToString();
                    // 将光标移动到最后一位
                    valueUI.CaretIndex = valueUI.Text.Length;
                    valueUI.TextChanged += fieldUI_TextChanged;
                    return;
                }
            } else {
                _value = valueUI.Text;
            }

            valueChanged?.Invoke(_value);
        }
    }
}
